//
//  ZCollectionView.m
//  OC-weibo
//
//  Created by zero on 17/3/25.
//  Copyright © 2017年 zero. All rights reserved.
//

#import "ZCollectionView.h"
#import "ZCollectionViewCell.h"

#define itemMargin 8
#define Margin 10
#define button ([UIScreen mainScreen].bounds.size.width - 2 * itemMargin - 2 * Margin) / 3

//  重用标识符
static NSString *cell_Coll = @"cell_Coll";

@interface ZCollectionView() <UICollectionViewDataSource>

@property (nonatomic,strong)UICollectionViewFlowLayout *layout;

@end

@implementation ZCollectionView

#pragma mark
#pragma mark - 重写init方法
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{
    
    if (self = [super initWithFrame:frame collectionViewLayout:layout]) {
        
        self.layout = (UICollectionViewFlowLayout *)layout;
     
        self.layout.itemSize = CGSizeMake(button, button);
        self.layout.minimumLineSpacing = Margin;
        self.layout.minimumInteritemSpacing = Margin;
        //  布局
        [self setupUI];
    }
    
    return self;
}


#pragma mark
#pragma mark - 布局
- (void)setupUI{
 
    //  数据源代理
    self.dataSource = self;
    
    //  注册
    [self registerClass:[ZCollectionViewCell class] forCellWithReuseIdentifier:cell_Coll];
    
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(100, 100));
        
    }];
}

#pragma mark
#pragma mark - 数据源代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.picModel.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell_Coll" forIndexPath:indexPath];
    
    cell.model = self.picModel[indexPath.item];
    
    return cell;
}


#pragma mark
#pragma mark - 获取大小
- (CGSize)getSize:(NSInteger)count{
    
    if (count != 1) {
        
        NSInteger row = (count-1) / 3 + 1;
        NSInteger col = count > 3 ? 3 : count;
        
        CGSize sizeForCollection = CGSizeMake(col * button + (col - 1) * Margin, row * button + (row - 1) * Margin);
        
//        NSLog(@"%@",NSStringFromCGSize(sizeForCollection));
        return sizeForCollection;
    }
//    NSLog(@"%@",NSStringFromCGSize(CGSizeMake(200, 200)));
    return CGSizeMake(200, 200);
}

#pragma mark
#pragma mark - set方法
- (void)setPicModel:(NSArray<ZPictureModel *> *)picModel{
    
    _picModel = picModel;
    
    
    CGSize itemSize = [self getSize:picModel.count];
    
    
   [self mas_updateConstraints:^(MASConstraintMaker *make) {
       
       make.size.mas_equalTo(itemSize);
       
   }];
    
#warning layoutIfNeeded....
    [self layoutIfNeeded];
    
    [self reloadData];
}
@end
